import logging
import config
import requests
import json
from redis_connection import redis_conn as redis


_logger = logging.getLogger("SEND_ENT_MSG")


def send_to_user(target: str, message: str) -> bool:
    try:
        requests.post("https://qyapi.weixin.qq.com/cgi-bin/message/send",
                      params={"access_token": redis.hget(config.ENT_ACCESS_TOKEN, "token").decode()},
                      data=json.dumps({
                          "touser": target,
                          "msgtype": "text",
                          "agentid": config.ENT_APP_AGENT,
                          "text": {
                              "content": message
                          },
                          "safe": "0"
                      }, ensure_ascii=False).encode("utf-8"),
                      headers={"Content-Type": "application/json; charset=utf-8"})
        _logger.info(f"向 {target} 推送消息成功。")
        return True
    except requests.ConnectionError:
        _logger.error(f"向 {target} 推送消息失败。")
    return False
